# coding: utf-8

import random

import sys
sys.path.append('../3_data_structure')
from queue import Queue


class Printer(object):
    def __init__(self, ppm):
        self.pagerate = ppm
        self.current_task = None
        self.time_remaining = 0

    def tick(self):
        if self.current_task is not None:
            self.time_remaining = self.time_remaining - 1

            if self.time_remaining <= 0:
                self.current_task = None

    def busy(self):
        if self.current_task is not None:
            return True
        else:
            return False

    def start_next(self, task):
        self.current_task = task
        self.time_remaining = task.get_pages() * 60 / self.pagerate


class Task(object):
    def __init__(self, time):
        self.timestamp = time
        self.pages = random.randrange(1, 21)

    def get_stamp(self):
        return self.timestamp

    def get_pages(self):
        return self.pages

    def wait_time(self, current_time):
        return current_time - self.timestamp


def new_print_task():
    num = random.randrange(1, 181)
    if num == 180:
        return True
    else:
        return False


def simulation(num_seconds, page_per_minute):
    printer = Printer(page_per_minute)
    queue = Queue()
    waiting_times = []

    for current_second in range(num_seconds):
        if new_print_task():
            task = Task(current_second)
            queue.enqueue(task)

        if (not printer.busy()) and (not queue.is_empty()):
            next_task = queue.dequeue()
            waiting_times.append(next_task.wait_time(current_second))
            printer.start_next(next_task)

        printer.tick()

    average = sum(waiting_times) / len(waiting_times)
    print("Average Wait %6.2f secs %3d task remaining" % (average, queue.size()))


for i in range(10):
    simulation(3600, 5)
